package controllers;

import java.util.Arrays;
import java.util.List;

import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import services.DAO;

public class QueryTesterCtrl extends Controller {

	@Transactional
	public static Result query(String query, String params) {
		try {
			String[] splitted = params.trim().split(" +");
			Object p[] = new Object[splitted.length % 2 != 0 ? 0
					: splitted.length];
			for (int i = 0; i < p.length; i++) {

				try {
					Long l = Long.parseLong(splitted[i].toString().trim());
					p[i] = (Object) l;
				} catch (Exception e) {
					p[i] = splitted[i];
				}
			}
			List<Object> res = DAO.execute(query, -1, p);
			if (res.size() == 0)
				res = Arrays.asList((Object) new QueryTesterException(
						"Sin resultados"));
			System.out.println(res.get(0));
			return ok(Json.toJson(res));
		} catch (Exception e) {
			e.printStackTrace();
			return ok(Json.toJson(Arrays
					.asList((Object) new QueryTesterException(e.getMessage()))));
		}
	}

	public static class QueryTesterException {
		private String message;

		public QueryTesterException(String message) {
			this.message = message;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}
	}
}
